package com.pandas.community.controller;

import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.entity.DiscussPost;
import com.pandas.community.entity.Page;
import com.pandas.community.service.DiscussPostService;
import com.pandas.community.service.LikeService;
import com.pandas.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private LikeService likeService;

    // 给index页面返回要显示的帖子列表信息
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page){
        //Springmvc会自动将page注入model
        page.setPath("/index");
        page.setInfoAmount(discussPostService.getDisscussPostAmount(0));

        List<DiscussPost> list = discussPostService.getDiscussPost(0,page.getOffset(),page.getPageCapacity());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if(list != null){
            for(DiscussPost post : list){
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                map.put("user", userService.selectById(post.getUserid()));

                //查询点赞数
                long likeCount = likeService.getEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        return "/index";
    }

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage(){
        return "/error/500";
    }
}
